package handler

import (
	"album-api/internal/logic"
	"album-api/internal/svc"
	"album-api/internal/types"
	"errors"
	"fmt"
	tcom "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentyun/vod-go-sdk"
	"github.com/zeromicro/go-zero/rest/httpx"
	"io"
	common "listenboos-common"
	"listenboos-common/tools"
	"net/http"
	"os"
	"path/filepath"
)

type TrackHandler struct {
	svcCtx *svc.ServiceContext
}

func (h TrackHandler) uploadTrack(w http.ResponseWriter, r *http.Request) {
	newResult := common.NewResult()
	file, handler, err := r.FormFile("file")
	if err != nil {
		result := newResult.Deal(4101, errors.New("上传声音失败"))
		httpx.WriteJsonCtx(r.Context(), w, 4101, result)
		return
	}
	filePath := "D:/VScode/WorkSpace/listenbooks-go-gozero/sours"
	// 创建保存文件的目录（如果不存在则创建）
	err = os.MkdirAll(filePath, os.ModePerm)
	if err != nil {
		httpx.Error(w, err)
		return
	}
	md5 := tools.Md5(handler.Filename)
	ext := filepath.Ext(handler.Filename)
	fileName := md5 + ext
	// 生成文件保存路径
	dst, err := os.Create(filepath.Join(filePath, fileName))
	if err != nil {
		http.Error(w, "Unable to create the file on server", http.StatusInternalServerError)
		return
	}
	//out, err := os.Create(dst)
	_, err = io.Copy(dst, file)
	if err != nil {
		httpx.Error(w, err)
		return
	}
	defer file.Close()
	defer dst.Close()
	//假设只上传一个文件
	client := &vod.VodUploadClient{}
	client.SecretId = h.svcCtx.Config.Tencent.SecretId
	client.SecretKey = h.svcCtx.Config.Tencent.SecretKey
	req := vod.NewVodUploadRequest()
	req.MediaFilePath = tcom.StringPtr(filePath + "/" + fileName)
	rsp, err := client.Upload("ap-guangzhou", req)
	if err != nil {
		fmt.Println(err)
		return
	}
	go func() {
		err = os.Remove(filePath + "/" + fileName)
		if err != nil {
			// 如果删除失败，打印错误信息
			fmt.Printf("Error removing file: %v\n", err)
			return
		}
	}()
	var res types.UploadTrackResp
	res.MediaUrl = *rsp.Response.MediaUrl
	res.MediaFileId = *rsp.Response.FileId
	//url := "http://192.168.2.9:9009/" + res
	resp := newResult.Deal(res, nil)
	httpx.OkJsonCtx(r.Context(), w, resp)
	return
}

func (h TrackHandler) SaveTrackInfo(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.SaveTrackReq
	if err := httpx.ParseJsonBody(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewTrackLogicLogic(r.Context(), h.svcCtx)
	res, err := l.SaveTrackInfo(token, req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h TrackHandler) FindUserTrackPage(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.FindUserTrackReq
	if err := httpx.ParseJsonBody(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewTrackLogicLogic(r.Context(), h.svcCtx)
	res, err := l.FindUserTrackPage(token, req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑列表"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(res, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h TrackHandler) GetTrackInfoById(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.TrackInfoReq
	if err := httpx.ParsePath(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewCategoryLogic(r.Context(), h.svcCtx)
	resp, err := l.GetTrackInfoById(token, req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到专辑的信息"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(resp, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func (h TrackHandler) RemoveTrackInfo(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get("token")
	newResult := common.NewResult()
	if token == "" {
		result := newResult.NoLogin(208, "未登录")
		//newResult.Fail(208, "未登录")
		httpx.OkJsonCtx(r.Context(), w, result)
		return
	}
	var req types.RemoteTrackReq
	if err := httpx.ParsePath(r, &req); err != nil {
		httpx.ErrorCtx(r.Context(), w, err)
		return
	}
	l := logic.NewTrackLogicLogic(r.Context(), h.svcCtx)
	err := l.RemoveTrackInfo(token, req)
	if err != nil {
		result := newResult.Deal(4004, errors.New("未查到声音信息"))
		httpx.WriteJsonCtx(r.Context(), w, 4004, result)
		return
	}
	result := newResult.Deal(nil, err)
	httpx.OkJsonCtx(r.Context(), w, result)
	return
}

func NewTrackHandler(svcCtx *svc.ServiceContext) *TrackHandler {
	return &TrackHandler{
		svcCtx: svcCtx,
	}
}
